<template>
  <div class="container">
    <h3>vue+openlayers: 加载Google地图(多种形式)</h3>
    <h4>
      <el-button type="primary" size="mini" @click="gmap(1)">中文卫星标记</el-button>
      <el-button type="primary" size="mini" @click="gmap(2)">英文卫星无标记</el-button>
      <el-button type="success" size="mini" @click="gmap(3)">地形图</el-button>
      <el-button type="success" size="mini" @click="gmap()">带标签地形图</el-button>
      <el-button type="danger" size="mini" @click="gmap(4)">改变的路线图（路线不明显）</el-button>
      <el-button type="danger" size="mini" @click="gmap(5)">标准路线图</el-button>
    </h4>
    <div id="vue-openlayers"></div>
  </div>
</template>

<script>
import 'ol/ol.css'
import { Map, View } from 'ol'
import { Tile } from 'ol/layer'
import { XYZ } from 'ol/source'
import { useGeographic, fromLonLat, toLonLat, transform } from 'ol/proj' // useGeographic: 使用地理坐标系, fromLonLat: 经纬度转换为投影坐标系, toLonLat: 投影坐标系转换为经纬度, transform: 坐标系转换
export default {
 data() {
   return {
     map: null,
     source: new XYZ({
      crossOrigin: 'anonymous', // 跨域
     })
   }
 },
 mounted() {
  this.initMap()
  this.gmap()
 },
 methods: {
  gmap(n) {
    this.source.clear()
    let url;
    switch(n) {
      case 1: // 中文卫星标记
        url = 'https://www.google.com/map/vt?lyrs=y&gl=cn&x={x}&y={y}&z={z}'
        break;
      case 2: // 英文卫星无标记
        url = 'https://mt3.google.com/maps/vt?lyrs=s&gl=en&x={x}&y={y}&z={z}'
        break;
      case 3: // 地形图
        url = 'https://www.google.com/maps/vt?lyrs=t&gl=en&x={x}&y={y}&z={z}'
        break;
      case 4: // 改变的路线图（路线不明显）
        url = 'https://www.google.com/maps/vt?lyrs=r&gl=en&x={x}&y={y}&z={z}'
        break;
      case 5: // 标准路线图
        url = 'https://www.google.com/maps/vt?lyrs=m&gl=en&x={x}&y={y}&z={z}'
        break;
      default: // 带标签地形图
        url = 'https://www.google.com/maps/vt?lyrs=p&gl=en&x={x}&y={y}&z={z}'
    }
    this.source.setUrl(url)
  },
  initMap() {
    let google = new Tile({ // 图层
      source: this.source
    })
    this.map = new Map({
      target: 'vue-openlayers',
      layers: [google],
      view: new View({
        center: [13247019.404399557, 4721671.572580107],
        zoom: 7
      })
    })
  }
 }
}
</script>

<style lang="scss" scoped>
.container {
    width: 840px;
    height: 550px;
    margin: 50px auto;
    border: 1px solid #ccc;
    #vue-openlayers {
      width: 800px;
      height: 420px;
      margin: 0 auto;
      border: 1px solid #42b983;
      position: relative;
    }
  }
</style>